package com.example.its2021606134chh.fragment;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.core.app.NotificationCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.example.its2021606134chh.HttpUtil;
import com.example.its2021606134chh.LifeIndexModule.IndexViewPagerAdapter;
import com.example.its2021606134chh.R;
import com.example.its2021606134chh.ThresholdModule.ThresholdParams;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link RealTimeEnvironmentFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RealTimeEnvironmentFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private ViewPager viewPager;
    private TextView tvPM25;
    private TextView tvLight;
    private TextView tvTemp;
    private LayoutInflater inflater;
    private View viewPm25, viewLightIntensity, viewTemperature;
    private List<View> listView = new ArrayList<>();
    private IndexViewPagerAdapter adapter;
    private LineChart lineTemperature, lineLightIntensity, linePm25;
    private List<String> X_label = new ArrayList<>();   //X轴字符
    private List<Entry> entriesY_Temperature = new ArrayList<>()
            , entriesY_LightIntensity = new ArrayList<>(),
            entriesY_Pm25 = new ArrayList<>();   //节点 Entry为折线上的点
    private List<Integer> colorsTemperature  = new ArrayList<>(),
            colorsLightIntensity = new ArrayList<>(),
            colorsPm25 = new ArrayList<>();
    private LineDataSet dataSetTemperature, dataSetLightIntensity, dataSetPm25;   //折线
    private NotificationManager notificationManager;    //状态栏通知

    public RealTimeEnvironmentFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RealTimeEnvironmentFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static RealTimeEnvironmentFragment newInstance(String param1, String param2) {
        RealTimeEnvironmentFragment fragment = new RealTimeEnvironmentFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_real_time_environment, container, false);
        inflater = LayoutInflater.from(getActivity());
        viewPager = (ViewPager) view.findViewById(R.id.viewPager);
        tvPM25 = (TextView) view.findViewById(R.id.tvPM25);
        tvLight = (TextView) view.findViewById(R.id.tvLight);
        tvTemp = (TextView) view.findViewById(R.id.tvTemp);
        notificationManager = (NotificationManager)getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        viewTemperature = inflater.inflate(R.layout.layout_rt_temperature, null);
        viewLightIntensity = inflater.inflate(R.layout.layout_rt_light, null);
        viewPm25 = inflater.inflate(R.layout.layout_rt_pm25, null);
        lineTemperature = viewTemperature.findViewById(R.id.lineTemperature);
        lineLightIntensity = viewLightIntensity.findViewById(R.id.lineLightIntensity);
        linePm25 = viewPm25.findViewById(R.id.linePm25);

        listView.add(viewTemperature);
        listView.add(viewLightIntensity);
        listView.add(viewPm25);
        adapter = new IndexViewPagerAdapter(listView);
        viewPager.setAdapter(adapter);

        X_label = new ArrayList<>();    //下标
        colorsTemperature = new ArrayList<>();
        colorsLightIntensity = new ArrayList<>();
        colorsPm25 = new ArrayList<>();

        entriesY_Temperature = new ArrayList<Entry>();
        lineTemperature.getLegend().setEnabled(false);  //显示图例
        XAxis xAxisTemperature = lineTemperature.getXAxis();    //刻度
        xAxisTemperature.setPosition(XAxis.XAxisPosition.BOTTOM);   //X轴位置
        xAxisTemperature.setValueFormatter(new IndexAxisValueFormatter() {   //X轴刻度
            @Override
            public String getFormattedValue(float value, AxisBase axisBase) {
                return X_label.get((int)value);
            }
        });

        entriesY_LightIntensity = new ArrayList<Entry>();
        lineLightIntensity.getLegend().setEnabled(false);  //显示图例
        XAxis xAxisLightIntensity = lineLightIntensity.getXAxis();    //刻度
        xAxisLightIntensity.setPosition(XAxis.XAxisPosition.BOTTOM);   //X轴位置
        xAxisLightIntensity.setValueFormatter(new IndexAxisValueFormatter() {   //X轴刻度
            @Override
            public String getFormattedValue(float value, AxisBase axisBase) {
                return X_label.get((int)value);
            }
        });

        entriesY_Pm25 = new ArrayList<Entry>();
        linePm25.getLegend().setEnabled(false);  //显示图例
        XAxis xAxisPm25 = linePm25.getXAxis();    //刻度
        xAxisPm25.setPosition(XAxis.XAxisPosition.BOTTOM);   //X轴位置
        xAxisPm25.setValueFormatter(new IndexAxisValueFormatter() {   //X轴刻度
            @Override
            public String getFormattedValue(float value, AxisBase axisBase) {
                return X_label.get((int)value);
            }
        });

        // Inflate the layout for this fragment
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                HttpUtil.asyncRequest(new HttpUtil.AsyncCallBack() {
                    @Override
                    public void onFailure(Exception e) {

                    }

                    @Override
                    public void onResponse(String json) {
                        Gson gson = new Gson();
                        ThresholdParams params = gson.fromJson(json, ThresholdParams.class);
                        int Temperature = Integer.parseInt(params.getTemperature());
                        int Pm25 = Integer.parseInt(params.getPm25());
                        int LightIntensity = Integer.parseInt(params.getLightIntensity());
                        int count = X_label.size();
                        if (count == 0) {
                            X_label.add("3");
                        } else {
                            X_label.add(String.valueOf(Integer.parseInt(X_label.get(count - 1)) + 3));
                        }

                        entriesY_Temperature.add(new Entry(count, Temperature));   //添加节点
                        dataSetTemperature = new LineDataSet(entriesY_Temperature, "Temperature");
                        if (Temperature > 24) {
                            colorsTemperature.add(Color.RED);
                        } else {
                            colorsTemperature.add(Color.GREEN);
                        }
                        dataSetTemperature.setCircleColors(colorsTemperature);
                        dataSetTemperature.setDrawCircleHole(false);    //实心
                        lineTemperature.setData(new LineData(dataSetTemperature));
                        lineTemperature.invalidate();

                        entriesY_LightIntensity.add(new Entry(count, LightIntensity));   //添加节点
                        dataSetLightIntensity = new LineDataSet(entriesY_LightIntensity, "LightIntensity");
                        if (LightIntensity > 2500) {
                            colorsLightIntensity.add(Color.RED);
                        } else {
                            colorsLightIntensity.add(Color.GREEN);
                        }
                        dataSetLightIntensity.setCircleColors(colorsLightIntensity);
                        dataSetLightIntensity.setDrawCircleHole(false);    //实心
                        lineLightIntensity.setData(new LineData(dataSetLightIntensity));
                        lineLightIntensity.invalidate();

                        entriesY_Pm25.add(new Entry(count, Pm25));   //添加节点
                        dataSetPm25 = new LineDataSet(entriesY_Pm25, "PM2.5");
                        if (Pm25 > 200) {
                            colorsPm25.add(Color.RED);
                            Notification notification = new Notification();
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                NotificationChannel mChannel = new NotificationChannel("pm25", "sensor", NotificationManager.IMPORTANCE_HIGH);
                                notificationManager.createNotificationChannel(mChannel);
                                notification = new Notification.Builder(getActivity(), null)
                                        .setChannelId("pm25")
                                        .setContentTitle("PM2.5警告")
                                        .setContentText("当前PM2.5:" + Pm25)
                                        .setSmallIcon(R.drawable.ic_launcher_background)
                                        .build();
                            } else {
                                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getActivity(), null)
                                        .setContentTitle("PM2.5警告")
                                        .setContentText("当前PM2.5:" + Pm25)
                                        .setSmallIcon(R.drawable.ic_launcher_background)
                                        .setOngoing(true);
                                try {
                                    notification = notificationBuilder.build();
                                } catch (Exception e) {
                                    Log.e("TAG", "AndroidRuntime");
                                }
                                
                            }
                            notificationManager.notify(1, notification);
                        } else {
                            colorsPm25.add(Color.GREEN);
                        }
                        dataSetPm25.setCircleColors(colorsPm25);
                        dataSetPm25.setDrawCircleHole(false);    //实心
                        linePm25.setData(new LineData(dataSetPm25));
                        linePm25.invalidate();
                    }
                }, "get_all_sense", new String[]{"UserName"}, "user1");
            }
        };
        timer.schedule(timerTask, 0, 3000);

        final List<TextView> textViewList = new ArrayList<>();
        textViewList.add(tvTemp);
        textViewList.add(tvLight);
        textViewList.add(tvPM25);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < textViewList.size(); i++) {
                    if (position == i) {
                        textViewList.get(i).setBackgroundResource(R.drawable.radiobutton_on_background);
                    } else {
                        textViewList.get(i).setBackgroundResource(R.drawable.radiobutton_off_background);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {}
        });

        tvTemp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setCurrentItem(0);
            }
        });
        tvLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setCurrentItem(1);
            }
        });
        tvPM25.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setCurrentItem(2);
            }
        });

        return view;
    }

    private void initView() {

    }
}